package net.zigin.nhi.waste.view.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.olc.scan.ScanManager;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.android.CaptureActivity;

import net.zigin.nhi.waste.MainApplication;
import net.zigin.nhi.waste.bean.MenuVoBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.utils.BitmapUtils;
import net.zigin.nhi.waste.utils.DialogUtil;
import net.zigin.nhi.waste.utils.LogUtil;
import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.utils.OpenFile;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.scan.CodeListener;
import net.zigin.nhi.waste.scan.CodeReceiver;
import net.zigin.nhi.waste.view.widget.DialogManager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.paperdb.Paper;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.http.DownLoadManager;
import me.goldze.mvvmhabit.http.download.ProgressCallBack;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.Utils;
import okhttp3.ResponseBody;


/**
 * 扫码登录界面
 */
public class LoginActivity extends AppCompatActivity implements CodeListener {

    private EditText mAccount;
    private EditText mPassword;
    private Button mLogin;
    private LinearLayout mScanLogin;

    private CodeReceiver receiver;

    private List<MenuVoBean> menuList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (!isTaskRoot()) {
            if (getIntent() != null) {
                String action = getIntent().getAction();
                if (getIntent().hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                    finish();
                    return;
                }
            }
        }

        getUserInfo();
        initView();
        initReceiver();
        initData();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        ImmersionBar.with(this).init();
        mAccount = findViewById(R.id.account);
        mPassword = findViewById(R.id.password);
        mLogin = findViewById(R.id.login);
        mScanLogin = findViewById(R.id.scan_login);

    }

    /**
     * 初始化广播接收器
     */
    @SuppressLint("WrongConstant")
    private void initReceiver() {
        receiver = new CodeReceiver();
        receiver.setListener(this);
        registerReceiver(receiver, new IntentFilter("com.barcode.sendBroadcast"));
    }

    /**
     * 点击事件及接口
     */
    @SuppressLint("CheckResult")
    private void initData() {
//        mAccount.setText("1001");
//        mPassword.setText("123456");
//        mAccount.setText("18756271821");
//        mPassword.setText("271821");

        /**
         * 登录按钮点击事件
         */
        mLogin.setOnClickListener(v -> {
            if (StringUtil.isEmpty(mAccount.getText().toString())) {
                Toast.makeText(this, "请输入账号！", Toast.LENGTH_SHORT).show();
            } else if (StringUtil.isEmpty(mPassword.getText().toString())) {
                Toast.makeText(this, "请输入密码！", Toast.LENGTH_SHORT).show();
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("name", mAccount.getText().toString());
                map.put("password", mPassword.getText().toString());
                Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .login(map);
                DialogManager.getInstance().showLoading(this);
                HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        Log.i("登录", data);
                        DialogManager.getInstance().dismissLoading();
                        menuList.clear();
                        JSONObject object = JSON.parseObject(data);
                        menuList = JSONArray.parseArray(object.getString("menuVoList"), MenuVoBean.class);
                        if (menuList != null && menuList.size() > 0) {
                            Paper.book().write(Constants.MENULIST, menuList);
                        }
                        String userName = object.getString("name");
                        if (userName != null) {
                            Paper.book().write(Constants.USERNAME, userName);
                        }

                        String userStaffId = object.getString("userStaffId");
                        if (userStaffId != null) {
                            Paper.book().write(Constants.STAFFID, userStaffId);
                        }

                        String token = object.getString("token");
                        if (token != null) {
                            Paper.book().write(Constants.TOKEN, token);
                        }
                        Log.i("我的token", token);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
            }
        });

        /**
         * 扫码登录按钮点击事件
         */
        mScanLogin.setOnClickListener(v -> {
            if (MainApplication.scanManager != null) {
                //开启扫描
                Intent intent = new Intent();
                intent.setAction("com.barcode.sendBroadcastScan");
                sendBroadcast(intent);
            } else {
                Intent intent = new Intent(LoginActivity.this, CaptureActivity.class);
                startActivityForResult(intent, 1003);
            }
        });
    }

    /**
     * 登录跳转
     *
     * @param data 扫码结果
     */
    private void login(String data) {
        if (StringUtil.isNotEmpty(data)) {
            Map<String, Object> map = new HashMap<>();
            map.put("content", data);
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .loginWithQrCode(map);
            DialogManager.getInstance().showLoading(this);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String data) {
                    Log.i("扫码登录", data);
                    menuList.clear();
                    JSONObject object = JSON.parseObject(data);
                    menuList = JSONArray.parseArray(object.getString("menuVoList"), MenuVoBean.class);
                    if (menuList != null && menuList.size() > 0) {
                        Paper.book().write(Constants.MENULIST, menuList);
                    }

                    String userName = object.getString("name");
                    if (userName != null) {
                        Paper.book().write(Constants.USERNAME, userName);
                    }

                    String userStaffId = object.getString("userStaffId");
                    if (userStaffId != null) {
                        Paper.book().write(Constants.STAFFID, userStaffId);
                    }

                    String token = object.getString("token");
                    if (token != null) {
                        Paper.book().write(Constants.TOKEN, token);
                    }

                    Log.i("我的token", token);
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            });
        }
    }


    /**
     * 设置个人信息
     */
    private void getUserInfo() {
        String id = Paper.book().read(Constants.STAFFID);
        String token = Paper.book().read(Constants.TOKEN);
        if (id == null || token == null) {
            return;
        }

        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getStaffInfoById(token, id);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String data) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    /**
     * 广播回调监听扫码结果
     *
     * @param data 扫码结果
     */
    @Override
    public void getData(String data) {
        Log.i("扫码结果", data);
        login(data);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == 1003 && resultCode == RESULT_OK) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra("codedContent");
                Log.i("扫码结果：", content);
                login(content);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
            System.gc();
        }
        super.onDestroy();
    }
}
